# Author:: Alexandre Ribeiro de Souza (<alexandre@lumis.com.br>)

user = "tomcat" #node['authorization']['system']['user']
client = data_bag_item("client", Chef::Config[:node_name].split('-')[1])
lumisportal_dir = node['lumis']['lumisportal']['dir']
lumisportal_home = node['lumis']['lumisportal']['home']

create_dirs = [ lumisportal_home, lumisportal_dir, "#{lumisportal_dir}/lumisdata", "#{lumisportal_dir}/lumisdata/config", "#{lumisportal_dir}/lumisdata/data" ]

create_dirs.each do |create_dir|
  directory create_dir do
    group user
    owner user
    mode "0755"
    recursive true
  end
end

local_ip = node.attribute?('cloud') ? node.cloud['local_ipv4'] : node.ipaddress
nodedb_ip = local_ip

unless ["saas", "saas-dev"].include?(node.chef_environment)
  nodedb = search(:node, "tags:database* AND tags:client_#{Chef::Config[:node_name].split('-')[1]}").first
  nodedb_ip = nodedb.attribute?('cloud') ? nodedb.cloud['local_ipv4'] : nodedb.ipaddress
end

mount lumisportal_home do
  device "#{nodedb_ip}:#{lumisportal_home}"
  fstype "nfs"
  options "proto=udp,soft,intr,bg,timeo=20,noacl,noatime,nodiratime,rw"
  action [:mount, :enable]
  not_if { nodedb_ip == local_ip }
end

config_files = Dir.glob("#{lumisportal_home}/lumisdata/config/*") - [ "#{lumisportal_home}/lumisdata/config/lumisportalconfig.xml" ]
create_links = [ "www", "lumisdata/def", "lumisdata/data/files" ] + config_files

create_links.each do |create_link|
  create_link.gsub!("#{lumisportal_home}/", "")
  link "#{lumisportal_dir}/#{create_link}" do
    to "#{lumisportal_home}/#{create_link}"
    group user
    owner user
  end
end

http_port = 8080 + (node['lumis']['lumisportal']['ports'] * 100)

template "#{lumisportal_dir}/lumisdata/config/lumisportalconfig.xml" do
  source "#{node['lumis']['lumisportal']['version']}-lumisportalconfig.xml.erb"
  mode "0644"
  owner user
  group user
  variables(
    :serverid => "#{node['fqdn']}",
    :frameworkurl => "http://#{client['url']}",
    :defaultlocale => node['lumis']['lumisportal']['defaultlocale'],
    :htmlgenerationurl => "http://localhost:#{http_port}",
    :errorpage => node['lumis']['lumisportal']['errorpage'],
    :webrootpath => "#{lumisportal_home}/htdocs",
    :clusterconfig => node['lumis']['lumisportal']['clusterconfig'].gsub('$LUMISPORTAL_HOME', lumisportal_home)
  )
end
